var happyReaderImg = {
    setting:{
        bigImg: {
            width: 320,
            height: 320
        },
        smallImg: {
            width: 60,
            height: 60
        },
        picMode:{
            "width" : {
                scrollBarCtlWidth : [100,217,452,800],   //height = Math.ceil(width / 1.3)
                imgWidth : [86,265,546,1020],
                imgHeight : [60,184,420,700]
            },
            "height" : {
                scrollBarCtlWidth : [100,222,384,800],   //height = width * 1.3
                imgWidth : [80,200,354,770],
                imgHeight : [88,300,510,980]
            }
        }
    },
    imgData:{
        big:[],
        normal:[],
        small:[]
    },
    imgTitleData:{
        big:{}
    },
    imgAltData:{
        big:{}
    },
    picListData:{
        big:"bigPic",
        normal:"normalPic",
        small:"smallPic"
    },
    picMode:"width",
    picFactor:1.3,
    picCurData:{status:'',scrollBarLevel:2},
    inited:false,
    maskDiv:null,
	maskLastIdx:'',
	maskPicStatus:'big',
	checkedImgList:{},
    getData:function(contentDiv){
		function sort(imgArr,img){
            var flag = false;
            for(var rlen = imgArr.length-1,j=0; j<rlen; j++){
                if (imgW >= imgArr[j].naturalWidth){
                    imgArr.splice(j,0,img);
                    flag = true;
                    break;
                }
            }
            !flag && imgArr.push(img);
        }
        
		this.imgData = {big:[],normal:[],small:[]};
		
        var bigImgSetting = this.setting.bigImg, smallImgSetting = this.setting.smallImg;
        var imgs = contentDiv.getElementsByTagName("img");
        var wBigImg = [], hBigImg = [], unBigImg = [];
        var wNormalImg = [], hNormalImg = [], unNormalImg = [];
        var imgTitleDataIdx = [], imgAltDataIdx = [], imgDataIdx = {big:[],normal:[],small:[]};
        for(var i=0,imgCnt=imgs.length; i<imgCnt; i++){
            var img = imgs[i] , imgW = img.naturalWidth , imgH = img.naturalHeight, imgParent = img.parentNode;
            //set img link
            if (imgParent.tagName == "A"){
                img.setAttribute("clickurl",imgParent.href);
                img.setAttribute("clicktitle",imgParent.title);
            }
            //group imgs by size
            if (imgW >= bigImgSetting.width && imgH >= bigImgSetting.height){
                if (!$.inArray(img.src,imgDataIdx.big)){
                    if (imgW > imgH)
                        sort(wBigImg,img,"width");
                    else if(imgW < imgH)
                        sort(hBigImg,img,"height");
                    else
                        unBigImg.push(img);
                    
                    imgDataIdx.big.push(img.src);

                    if (!$.inArray(img.title, imgTitleDataIdx)){
                        this.imgTitleData.big[img.src] = img.title;
                        imgTitleDataIdx.push(img.title);
                    }
                    if (!$.inArray(img.alt, imgAltDataIdx)){
                        this.imgAltData.big[img.src] = img.alt;
                        imgAltDataIdx.push(img.alt);
                    }
                }
            }else if (imgW <= smallImgSetting.width && imgH <= smallImgSetting.height){
                if (!$.inArray(img.src,imgDataIdx.small)){
                    this.imgData.small.push(img);
                    imgDataIdx.small.push(img.src);
                }
            }else{
                if (!$.inArray(img.src,imgDataIdx.normal)){
                    if (imgW > imgH)
                        sort(wNormalImg,img,"width");
                    else if (imgW < imgH)
                        sort(hNormalImg,img,"height");
                    else
                        unNormalImg.push(img);
                            
                    imgDataIdx.normal.push(img.src);
                }
            }
        }

        this.picMode = (wBigImg.length > hBigImg.length) ? "width" : "height";
        var tmpImg = (this.picMode == "width") ? $.mergeArray(wBigImg, hBigImg) : $.mergeArray(hBigImg, wBigImg) ;
        this.imgData.big = $.mergeArray(tmpImg, unBigImg);
        
        tmpImg = (this.picMode == "width") ? $.mergeArray(wNormalImg, hNormalImg) : $.mergeArray(hNormalImg, wNormalImg);
        this.imgData.normal = $.mergeArray(tmpImg, unNormalImg);
    },
    init:function(){
        $('#happyReaderHeaderAD').html(_m("imgModeHeaderAD"));
		happyReader.setUserConfig("viewMode","img");
        if (this.inited)return ;
        this.inited = true;
        
        var rangeClassName = (document.compatMode == 'BackCompat') ? 'BackCompat' : '' ,
            imgHtml =
            '<div class="operate">'
                +'<b>'+_m("size")+'</b><input type="range" min="100" max="800" value="400" id="happyReaderScrollBar" class="" title="384 X 296">'
            +'</div>'
            +'<h2 id="bigLine" class="at">'+_m("big")+'({bigPicCount}) <a id="saveall_big" href>'+_m("saveAll")+'</a></h2><ul id="bigPic" class="picList"></ul>'
            +'<h2 id="normalLine">'+_m("normal")+'({normalPicCount}) <a id="saveall_normal" href>'+_m("saveAll")+'</a></h2><ul id="normalPic" class="picList"></ul>'
            +'<h2 id="smallLine">'+_m("small")+'({smallPicCount}) <a id="saveall_small" href>'+_m("saveAll")+'</a></h2><ul id="smallPic" class="picList"></ul>';
        
        imgHtml = imgHtml.replace('{bigPicCount}',this.imgData.big.length).replace('{normalPicCount}',this.imgData.normal.length).replace('{smallPicCount}',this.imgData.small.length);
        $('#imgCanvas').css({left:0}).html(imgHtml);
        
        $('#saveall_big').attr({onclick:function(e){e.stopPropagation();happyReaderImg.saveAll('big');return false;}});
        $('#saveall_normal').attr({onclick:function(e){e.stopPropagation();happyReaderImg.saveAll('normal');return false;}});
        $('#saveall_samll').attr({onclick:function(e){e.stopPropagation();happyReaderImg.saveAll('small');return false;}});
        this.setView();
        this.addListener();
		_gaq.push(['_trackEvent', 'HRImgUrl', location.href]);
    },
    render:function(){
        var factor = this.picCurData.scrollBarLevel - 1;
        var status = this.picCurData.status;
        var imgs = this.imgData[status], ul = document.getElementById(this.picListData[status]);
        var baseFactor = this.setting.picMode[this.picMode].scrollBarCtlWidth[factor];
        var defaultImgWidth = this.setting.picMode[this.picMode].imgWidth[factor], defaultImgHeight = this.setting.picMode[this.picMode].imgHeight[factor];
        ul.innerHTML = "";
        for(var i=0;i<imgs.length-1;i++){
            var img = imgs[i];
            var textHeight = (factor > 0) ? 24 : 0 ;  //default picMode is width 
            if (this.picMode == "height")
                textHeight = (factor > 0) ? 70 : 0 ; 
            var li = document.createElement("li");
			li.id = 'li_'+status+'_img_'+ i;
            li.style.width = ((this.picMode == "width") ? Math.ceil(baseFactor*this.picFactor) : baseFactor) + "px";
            li.style.height = ((this.picMode == "height") ? Math.ceil(baseFactor*this.picFactor) : baseFactor) +textHeight + "px"; 

            var imgHTML = "<img id='"+status+"_img_"+i+"' src="+img.src;
            if (img.naturalWidth > defaultImgWidth || img.naturalHeight > defaultImgHeight){
                if (img.naturalWidth > img.naturalHeight)
                    imgHTML += " width="+defaultImgWidth; 
                else
                    imgHTML += " height="+defaultImgHeight; 
            }
            imgHTML += " status='"+status+"' alt="+img.getAttribute('clicktitle')+" />";
            
            var letterCount = -5*(factor+1), checkboxID = status+'_check_'+i;
            var imgTitle = (status == "big") ? this.imgTitleData.big[img.src] : img.title;
            var imgAlt = (status == "big") ? this.imgAltData.big[img.src] : img.alt;
            var imgName = (imgAlt ? imgAlt.slice(letterCount) : null) || (imgTitle ? imgTitle.slice(letterCount) : null) || img.src.slice(letterCount);
            li.innerHTML = '<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">'
            +'<tr><td align="center" valign="middle">'+imgHTML+'<p class="photoBlank'+factor+'"><input id="'+checkboxID+'" type="checkbox" value="'+img.src+'"/><label for="'+checkboxID+'">'+imgName+'<br/>'+img.naturalWidth+'X'+img.naturalHeight+'</label></p><div class="tip"><tip><a id="'+status+'_save_'+i+'" href>'+_m('imgSaveCheckedImage')+'</a></tip></div></td></tr>'
            +'</table>';
            ul.appendChild(li);
            
            //$('#'+status+'_save_'+i).attr({onclick:function(){happyReaderImg.save(this.href);_gaq.push(['_trackEvent', 'imgSave::single', 'imgSave']);return false;}});
            $('#'+status+'_save_'+i).attr({onclick: function(){happyReaderImg.saveCheckedImg();_gaq.push(['_trackEvent', 'imgSave::checked', 'imgSave']);return false;}});
			$('#'+status+'_img_'+i).attr({onclick:function(){happyReaderImg.showMaskImg(this);_gaq.push(['_trackEvent', 'imgMask::show', 'imgMask']);}}).css({cursor:'pointer'});
            $('#'+status+'_check_'+i).attr({onclick:function(){happyReaderImg.checkboxHandle(this);_gaq.push(['_trackEvent', 'imgCheckbox::click', 'imgChecked']);}});
		}
    },
    setView:function(){
        var bigImgs = this.imgData.big, normalImgs = this.imgData.normal, smallImgs = this.imgData.small, 
            bigLine = $('#bigLine'), normalLine = $('#normalLine'), smallLine = $('#smallLine'), 
            bigPic = $('#bigPic'), normalPic = $('#normalPic'), smallPic = $('#smallPic'),
            _this = this;
        
        if (bigImgs.length > 0){
            this.picCurData.status = "big";
            bigPic.show();
            normalPic.hide();
            smallPic.hide();
            bigLine[0].onclick = function(){
                _this.viewSwitch(this);
            }
            normalLine[0].onclick = function(){
                _this.viewSwitch(this);
            }
            smallLine[0].onclick = function(){
                _this.viewSwitch(this);
            }
        }else if (normalImgs.length > 0){
            this.picCurData.status = "normal";
            bigPic.hide();
            normalPic.show();
            smallPic.hide();
            bigLine.attr({"className":""}).css({"cursor":"default"});
            normalLine.attr({"className":"at"});
            normalLine[0].onclick = function(){
                _this.viewSwitch(this);
            }
            smallLine[0].onclick = function(){
                _this.viewSwitch(this);
            }
        }else if (smallImgs.length > 0){
            this.picCurData.status = "small";
            bigPic.hide();
            normalPic.hide();
            smallPic.show();
            bigLine.attr({"className":""}).css({"cursor":"default"});
            normalLine.attr({"className":""}).css({"cursor":"default"});
            smallLine.attr({"className":"at"});
            smallLine[0].onclick = function(){
                _this.viewSwitch(this);
            }
        }
        this.render();
    },
    viewSwitch:function(obj){
        this.picCurData.status = obj.id.split("Line")[0];
        obj.nextSibling.style.display = (obj.className == "at") ? "none" : "block";
        obj.className = (obj.className == "at") ? "" : "at";
        _gaq.push(['_trackEvent', 'imgViewSwitch::type_'+this.picCurData.status+'_level_'+this.picCurData.scrollBarLevel+'_switch_'+(obj.className?'open':'close'), 'imgViewSwitch']);
        this.render();
    },
    addListener:function(){
        var _this = this,
            scrollBar = $("#happyReaderScrollBar")[0];
        
        scrollBar.onchange = function(e){
            var newLevel = Math.ceil(this.value / 200);
            if (newLevel == _this.picCurData.scrollBarLevel) {
                return;
            }
            
            _this.picCurData.scrollBarLevel = newLevel;
            var oldStatus = _this.picCurData.status;
            for(var key in _this.imgData){
                _this.picCurData.status = key;
                _this.render();
            }
            _this.picCurData.status = oldStatus;
            _gaq.push(['_trackEvent', 'imgScrollBarChanged::type_'+oldStatus+'_level_'+newLevel, 'imgScrollBarChanged']);
        }
        scrollBar.onmouseover = scrollBar.onmousemove = function(e){
            var position = Math.ceil((e.clientX-parseInt(_m("scrollBarOffset")))/30);
            var w = _this.setting.picMode[_this.picMode].scrollBarCtlWidth[position-1];
            this.title = w + " X " + ((_this.picMode == "width") ? Math.ceil(w*_this.picFactor): Math.ceil(w/_this.picFactor)) ;
        }
    },
    save:function(url){
        happyReader._downloadUrl(url);
    },
    saveAll:function(status){
        var imgs = document.getElementById(status+'Pic').getElementsByTagName('img');
        if (imgs.length){
            for(var i=0,img;img=imgs[i++];){
                happyReader._downloadUrl(img.src);
            }
        }
        _gaq.push(['_trackEvent', 'imgSave::all', 'imgSave']);
    },
	saveCheckedImg:function(){
       for (var idx in this.checkedImgList){
	       happyReader._downloadUrl(this.checkedImgList[idx]);
	   }
    },
    showMaskImg:function(self){
		var maskAvailSize = this.getMaskAvailSize(),
            maskAWidth = maskAvailSize.width, 
            maskAHeight = maskAvailSize.height,
			imgWidth = self.naturalWidth || self.width,
			imgHeight = self.naturalHeight || self.height,
            imgMode = maskAWidth / imgWidth * imgHeight > maskAHeight ? 'height' : 'width',
            imgWidth2height = imgWidth/imgHeight,
			imgAttrWidth = Math.min(imgWidth, maskAWidth),
            imgAttrHeight = Math.min(imgHeight, maskAHeight),
            imgAttr = imgMode == 'width' ? 
                     {width:imgAttrWidth, height:1/imgWidth2height*imgAttrWidth} : 
                     {width:imgWidth2height*imgAttrHeight, height:imgAttrHeight};
	    
		this.maskPicStatus = self.getAttribute('status');
		if (!this.maskDiv){
            var html = "<div id='maskCanvas'><b id='closeMask'>X</b><img id='maskCanvasImg' /></div>"
            +"<div id='maskBar'>"
			  +"<span id='maskCurImgIdx'></span>"
              +"<span id='maskBarLarger'>"+_m('imgPPTLarger')+"</span>"
              +"<span id='maskBarSmaller'>"+_m('imgPPTSmaller')+"</span>"
              +"<span id='maskBarSave'>"+_m('imgPPTSavePhoto')+"</span>"
              +"<span id='maskBarBack'>"+_m('imgPPTBack')+"</span>"
            +"</div>";
			
            this.maskDiv = $.createEle('div', {id:'happyReaderImgMask',onclick:function(){happyReaderImg.hideMaskImg()}}, {position:'absolute', top:0, left:0, width:'100%', height:'100%', background:'rgba(0,0,0,.7)'}).html(html).appendTo($('body'));
            $('#maskBar').attr({onclick:function(e){e.stopPropagation();return false;}});
			$('#maskBarSave').attr({onclick: function(){happyReaderImg.save(self.src);_gaq.push(['_trackEvent', 'imgMaskBtn::save', 'imgMaskBtn']);}});
            $('#maskBarBack').attr({onclick: function(){happyReaderImg.hideMaskImg();_gaq.push(['_trackEvent', 'imgMaskBtn::back', 'imgMaskBtn']);}});
        }
		happyReader.hideHeader();
        
        var curIdx = self.id.split('_').pop(),
		    marginTopValue = imgAttr.height ? (maskAHeight - imgAttr.height)/2+'px' : 0,
			maskImg = $('#maskCanvasImg').attr({onmousemove:function(e){happyReaderImg.setMaskImgCursor(e, this)}}).css({opacity:0});
			
		this.setMaskCurImgIdx(curIdx);
		this.setHighLight(curIdx);
		
		setTimeout(function(){
			maskImg.attr({src:self.src}).css({opacity:1, marginTop:marginTopValue}).attr(imgAttr)[0].setAttribute('idx', curIdx);
			happyReaderImg.showCloseBtn(imgAttr, maskAvailSize);
			setTimeout(function(){happyReaderImg.initMaskBarZoom();},500);
		},300);
		
        this.maskDiv.css({top:document.body.scrollTop+'px'}).show();
        $('body').css({'overflow-y':'hidden'});
		
		window.onmousewheel = function(e){
            if (e.wheelDelta > 0){
                happyReaderImg.preMaskImg();
            }else{
                happyReaderImg.nextMaskImg();
            }
			_gaq.push(['_trackEvent', 'imgMask::mousewheel', 'imgMask', 'wheelDelta_'+e.wheelDelta]);
        }
    },
    hideMaskImg:function(){
        window.onmousewheel = null;
		$('#maskCanvasImg').attr({width:0,height:0}).css({marginTop:0});
		this.hideCloseBtn();
		happyReader.showHeader();
		setTimeout(function(){
			happyReaderImg.maskDiv.hide();
			happyReaderImg.clearHighLight();
            $('body').css({'overflow-y':'auto'});
		},700);
        _gaq.push(['_trackEvent', 'imgMask::hide', 'imgMask']);
    },
    preMaskImg:function(){
		var curIdx = $('#maskCanvasImg')[0].getAttribute('idx');
		if (curIdx <= 0)return;
        this.clearHighLight();
		this.showMaskImg($('#'+this.maskPicStatus+'_img_'+(--curIdx))[0]);
        _gaq.push(['_trackEvent', 'imgMaskBtn::pre', 'imgMaskBtn', 'curIdx_'+curIdx]);
    },
    nextMaskImg:function(){
		var curIdx = $('#maskCanvasImg')[0].getAttribute('idx');
		if (curIdx >= this.imgData[this.maskPicStatus].length - 1)return;
        this.clearHighLight();
		this.showMaskImg($('#'+this.maskPicStatus+'_img_'+(++curIdx))[0]);
        _gaq.push(['_trackEvent', 'imgMaskBtn::next', 'imgMaskBtn', 'curIdx_'+curIdx]);
    },
	setHighLight: function(idx){
		this.maskLastIdx = idx;
		$('#li_'+this.maskPicStatus+'_img_'+idx).attr({className:'cur'});
	},
	clearHighLight: function(idx){
		idx = idx || this.maskLastIdx;
		$('#li_'+this.maskPicStatus+'_img_'+idx).attr({className:''});
	},
	setMaskCurImgIdx: function(idx){
		idx = parseInt(idx) + 1 + '/' + this.imgData[this.maskPicStatus].length;
		$('#maskCurImgIdx').html(idx);
	},
	setMaskImgCursor:function(e, self){
		var _this = this,
		    curIdx = self.getAttribute('idx'),
		    isLeft = window.screen.availWidth/2 > e.clientX;

		self.className = isLeft ? 
		                 (curIdx <=0 ? '' : 'pre') : 
						 (curIdx >= _this.imgData[_this.maskPicStatus].length - 1 ? '' : 'next');

		self.onclick = function(e){
			e.stopPropagation();
            isLeft ? happyReaderImg.preMaskImg() : happyReaderImg.nextMaskImg();
			return false;		
		}
	},
	getMaskAvailSize:function(){
		var scr = window.screen;
	    return {width: scr.availWidth - 40, height: scr.availHeight - 105};//25 + 80
	},
	setMaskImgLarger:function(){
		this.resizeMaskImg(1);
	},
	setMaskImgSmaller:function(){
		this.resizeMaskImg(-1);
	},
	initMaskBarZoom:function(){
		this.resizeMaskImg(0);
	},
	resizeMaskImg:function(zoom){
		var seed = 1.15, 
		    newFactor = Math.pow(seed, zoom), 
			maskImg = $('#maskCanvasImg'), 
			newWidth = maskImg.attr('width') * newFactor, 
			newHeight = maskImg.attr('height') * newFactor,
			imgSize = {width: newWidth, height: newHeight},
			nextFactor = zoom ? newFactor : seed,
			nextWidth = newWidth * nextFactor, 
			nextHeight = newHeight * nextFactor, 
			maskAvailSize = this.getMaskAvailSize(), 
			maskAWidth = maskAvailSize.width, 
			maskAHeight = maskAvailSize.height, 
			marginTopValue = (maskAHeight - newHeight) / 2 + 'px';
		
		if (zoom != 0) {	
			this.setCloseBtnPos(imgSize, maskAvailSize);
			maskImg.attr(imgSize).css({marginTop: marginTopValue});
		}
		
        var cssEnable = {cursor:'pointer', color:''}, 
            cssDisable = {cursor:'', color:'#ccc'},
            largerCss = cssEnable,
            smallerCss = cssEnable, 
            largerAttr = {onclick: function(){happyReaderImg.setMaskImgLarger();_gaq.push(['_trackEvent', 'imgMaskBtn::zoom+', 'imgMaskBtn', 'zoom+']);}},
            smallerAttr = {onclick: function(){happyReaderImg.setMaskImgSmaller();_gaq.push(['_trackEvent', 'imgMaskBtn::zoom-', 'imgMaskBtn', 'zoom-']);}},
            attrDisable = {onclick:null};
        
		if (nextWidth > maskAWidth || nextHeight > maskAHeight) {
			largerAttr = attrDisable;
			largerCss = cssDisable;
		}else if (nextWidth < 100 || nextHeight < 100) {
			smallerAttr = attrDisable;
			smallerCss = cssDisable;
		}

        $('#maskBarSmaller').attr(smallerAttr).css(smallerCss);
        $('#maskBarLarger').attr(largerAttr).css(largerCss);
	},
	setCloseBtnPos:function(imgSize, maskAvailSize){
		var topValue = (maskAvailSize.height - imgSize.height)/2 + 'px',
		    rightValue = (maskAvailSize.width - imgSize.width)/2 + 'px';
		$('#closeMask').css({top:topValue, right:rightValue});
	},
	showCloseBtn:function(imgSize, maskAvailSize){
		this.setCloseBtnPos(imgSize, maskAvailSize);
		setTimeout(function(){
			$('#closeMask').show();
		},550);
	},
	hideCloseBtn:function(){
		$('#closeMask').hide();
	},
	checkModeValid:function(){
		return this.imgData.big.length > 2;
	},
	checkboxHandle:function(self){
		var checked = self.checked, 
		    info = self.id.split('_'),
			status = info.shift(),
			idx = info.pop(),
			imgLi = $('#li_'+status+'_img_'+idx);
			
		if (checked){
			imgLi.attr({className:'cur'});
			this.checkedImgList[idx] = self.value;
			var tipStyle = imgLi[0].getElementsByTagName('tip')[0].style;
			tipStyle.top = '-42px';
			tipStyle.opacity = 1;
			setTimeout(function(){
				tipStyle.top = 0;
				tipStyle.opacity = 0;
			},2000);
		}else{
			imgLi.attr({className:''});
			delete this.checkedImgList[idx];
		}
	}
};